Shader "Prota/BlurMip"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" { }
        _Mask ("Mask", 2D) = "white" { }
        
        _Level0 ("Level 0", vector) = (1, 0, 0, 0)
        _Level1 ("Level 1", vector) = (1, 0, 0, 0)
        _Level2 ("Level 2", vector) = (1, 0, 0, 0)
        _Level3 ("Level 3", vector) = (1, 0, 0, 0)
        _Level4 ("Level 4", vector) = (1, 0, 0, 0)
        _Level5 ("Level 5", vector) = (1, 0, 0, 0)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };
            
            sampler2D _MainTex;
            float4 _MainTex_TexelSize;
            
            sampler2D _Mask;
            
            // 数字代表 LOD level.
            // x: mask = 1 的时候该等级LOD权重.
            // y: mask = 0 的时候该等级LOD权重.
            float4 _Level0;
            float4 _Level1;
            float4 _Level2;
            float4 _Level3;
            float4 _Level4;
            float4 _Level5;
            

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                float4 mask = tex2D(_Mask, i.uv);
                
                float4 levels[] = {
                    _Level0,
                    _Level1,
                    _Level2,
                    _Level3,
                    _Level4,
                    _Level5
                };
                
                float totalWeight = 0;
                float4 color = float4(0, 0, 0, 0);
                for(int k = 0; k < 6; k++)
                {
                    float4 level = levels[k];
                    float4 texel = tex2Dlod(_MainTex, float4(i.uv, 0, k));
                    float weight = lerp(level.y, level.x, mask.r);
                    color += texel * weight;
                    totalWeight += weight;
                }

                return color / max(1e-6, totalWeight);
            }
            ENDCG
        }
    }
    FallBack "Diffuse"
}
